package com.telra.app.server.jms;
import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;

import com.telra.app.server.protobuff.QueryRequestProto;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.impl.Log4JLogger;


public class Query {

    private static final Log4JLogger log = (Log4JLogger) LogFactory.getFactory().getInstance(Query.class);

    public Query(String key) {

        QueryRequestProto.QueryRequest req = QueryRequestProto.QueryRequest.newBuilder().setOrderidKey(key).build();

        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616");
        connectionFactory.setUseAsyncSend(false);	//blocking call

        try {
            Connection connection = connectionFactory.createConnection();
            connection.start();

            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

            Destination tempDest = session.createTemporaryQueue();
            MessageConsumer responseConsumer = session.createConsumer(tempDest);
            responseConsumer.setMessageListener(new MessageListener() {
                public void onMessage(Message m) {
                    log.info("query result received: " + m);
                }
            });

            MessageProducer producer = session.createProducer(session.createQueue("QUERY.OUT"));
            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

            ObjectMessage bMessage = session.createObjectMessage();
            bMessage.setObject(req);
            bMessage.setJMSReplyTo(tempDest);

            producer.send(bMessage);

            log.info("send query request");
        }

        catch (JMSException e) {
            e.printStackTrace();
        }

    }

}
